package user

import (
	"github.com/labstack/echo"
	"tacitus/library/error"
	"tacitus/library/format"
	resp "tacitus/library/response"
)

type ListItem struct {
	User
	Sex      string    `json:"sex"`       // 性别:0,未设置;1,男;2,女
	Birthday string  `json:"birthday"`  // 出生日期
	HeadFile string `json:"head_file"`
	CreateTime string `json:"create_time"`
}

func ShowUserListHandler(c echo.Context) error {
	i := new(struct{
		Keyword string `json:"keyword"`
		resp.PageFields
	})
	if err := c.Bind(i); err != nil {
		return err
	}
	s := x.NewSession()
	if i.Keyword != "" {
		kw := "%"+i.Keyword+"%"
		s.Where("account LIKE ? OR mobile LIKE ? OR nick_name LIKE ?", kw, kw, kw)
	}
	data := make([]User, 0)
	count, err := s.Limit(i.Size(), i.Offset()).FindAndCount(&data)
	if err != nil {
		return errs.Report("xorm", err)
	}
	res := make([]ListItem, len(data))
	his := make([]int64, len(data))
	for index, item := range data {
		res[index] = ListItem{User: item, Sex: Sex(item.Sex), Birthday: format.Date(item.Birthday), CreateTime: format.DateTime(item.CreateTime)}
		his[index] = item.HeadID
	}
	hm, err := MatchUserHeadFile(his)
	if err != nil {
		return err
	}
	for index, item := range res {
		res[index].HeadFile = hm[item.HeadID]
	}
	return resp.Page(c, res, *i.SetItemCount(int(count)))
}

func ResetUserPasswordHandler(c echo.Context) error {
	i := new(struct{
		UserID int64 `json:"user_id"`
	})
	if err := c.Bind(i); err != nil {
		return err
	}
	u := new(User)
	if ok, err := x.Where("id = ?", i.UserID).Get(u); err != nil {
		return err
	} else if !ok {
		return errs.Called("用户不存在")
	}
	// 生成随机的新密码
	password := RandPassword()
	salt := RandSlat()
	if _, err := x.Where("id = ?", i.UserID).Update(&User{
		Password: EncryptPassword(password, salt),
		Salt:     salt,
	}); err != nil {
		return err
	}
	return resp.Data(c, echo.Map{
		"password": password,
	})
}
